package com.example.calendarapp;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.AdapterView.OnItemSelectedListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * This class consists of a method that allows the user to
 * add and create events in the calendar application. It allows 
 * the user to be able to add the event during monthly view,
 * weekly view, and day view. It will display an error message
 * if it can't add the event. 
 *
 * @author Emilio Celis-Aguirre
 * @author Jeremy Henderson
 * @author Felipe Luna
 * @author Nathan Whitaker
 * @author Xiaoxu Zhang
 */
public class EventCreateFragment extends Fragment implements OnItemSelectedListener {
	private EventsDataSource data;
	private String[] hours = {"12AM", "1AM", "2AM", "3AM", "4AM", "5AM", "6AM", "7AM", "8AM",
			 				"9AM", "10AM", "11AM", "12PM", "1PM", "2PM", "3PM", "4PM", "5PM",
			 				 "6PM", "7PM", "8PM", "9PM", "10PM", "11PM"};
	private String[] dayStrings = {"None", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
	private List<Integer> years = new ArrayList<Integer>();
	private List<String> endHours = new ArrayList<String>();
	private List<Integer> days = new ArrayList<Integer>();
	private Integer[] months = {1,2,3,4,5,6,7,8,9,10,11,12};
    private ArrayAdapter<Integer> monthAdapter = null; 
    private ArrayAdapter<Integer> dayAdapter = null;
    private ArrayAdapter<Integer> yearAdapter = null;
    private ArrayAdapter<String> hourEndAdapter = null;
	private static Calendar c = Calendar.getInstance();
	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	private Spinner cat, hourStart, hourEnd, year, month, day, repeat;
	private EditText name;
	private EditText desc;
	private TextView date;
	
	
	/**
	* This method allows the creation of an event when the 
	* user clicks on the desired date and time. It consists 
	* of a method that will add the event and will display
	* an error message if the event can't be added. 
	* @param inflater
	* @param container
	* @param savedInstanceState
	* @return v
	*/	
		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		ActionBar actionBar = getActivity().getActionBar();
    	actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

		
		View v = inflater.inflate(R.layout.eventcreatefragment, container, false);
		Bundle bundle = getArguments();
		String dateString = "";
		if(bundle != null)
		{
			dateString = bundle.getString("date");
//    		Toast.makeText(getActivity(), dateString, Toast.LENGTH_SHORT).show();

		}
		
        if(dateString != "")
        {
        	try
        	{
        		c.setTime(df.parse(dateString));
        	}catch(Exception e){
        	}
        }
        
		
		for(int i = 2000; i < 2100; i++)
		{
			years.add(i);
		}
		data = EventsDataSource.getInstance(getActivity());
		data.createDatabase();
		data.open();
		List<String> catStrings = data.getCategoriesStrings();

		name = (EditText) v.findViewById(R.id.eventNameET);
		
		hourStart = (Spinner) v.findViewById(R.id.hourStart);
	    hourEnd = (Spinner) v.findViewById(R.id.hourEnd);
		year = (Spinner) v.findViewById(R.id.year);
        month = (Spinner) v.findViewById(R.id.month);
        cat = (Spinner) v.findViewById(R.id.eventCat);
        day = (Spinner) v.findViewById(R.id.day);
        repeat = (Spinner) v.findViewById(R.id.repeatDay);
        
        yearAdapter = new ArrayAdapter<Integer>(
				getActivity(), android.R.layout.simple_spinner_item, years);
		monthAdapter = new ArrayAdapter<Integer>(
				getActivity(), android.R.layout.simple_spinner_item, months); 		
		ArrayAdapter<String> hourStartAdapter = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item, hours);
		ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item, catStrings);
		ArrayAdapter<String> dayStringAdapter = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item, dayStrings);
		
		year.setAdapter(yearAdapter);
        month.setAdapter(monthAdapter);
    	hourStart.setAdapter(hourStartAdapter);
    	cat.setAdapter(categoryAdapter);
    	repeat.setAdapter(dayStringAdapter);
		
    	hourStart.setOnItemSelectedListener(this);
        year.setOnItemSelectedListener(this);
        month.setOnItemSelectedListener(this);
        repeat.setOnItemSelectedListener(this);
        
        
        year.setSelection(c.get(Calendar.YEAR)-2000);
        month.setSelection(c.get(Calendar.MONTH));
        
        Button btn = (Button) v.findViewById(R.id.addButt);
        btn.setOnClickListener( new OnClickListener() { 
         
	        	/**
				 * This method will add the event to the desired date and time
				 * when the user clicks on the button. It will display an error 
				 * message if the event can't be added.
				 * @param v		View v
				 */
	        	
                    @Override 
                    public void onClick(View v) {
                    	if(name.getText().toString().trim().length() != 0)
                    	{
                    		if(repeat.getSelectedItemPosition() == 0)
                    		{
	                    		
	                    		if(!data.add(name.getText().toString(),(int) year.getSelectedItem(),(int) month.getSelectedItem(), 
	                    				(int)day.getSelectedItem(), hourStart.getSelectedItemPosition(), hourEnd.getSelectedItemPosition()+1,
	                    				cat.getSelectedItemPosition(), c.get(Calendar.DAY_OF_WEEK)-1))
	                    		{
	                    			Toast.makeText(getActivity(), "Can't Add!", Toast.LENGTH_SHORT).show();
	                    		}
	                    		else
	                    			getFragmentManager().popBackStack();
                    		}
                    		else
                    		{

                    			if(!data.addRepeated(name.getText().toString(), (int) hourStart.getSelectedItemPosition(), hourEnd.getSelectedItemPosition() + 1,
                    					cat.getSelectedItemPosition(), c.get(Calendar.DAY_OF_WEEK)-1))
                    			{
                    				Toast.makeText(getActivity(), "Can't Add!", Toast.LENGTH_SHORT).show();
                    			}
                    			else
                    				getFragmentManager().popBackStack();
                    		}
                    	}
                    	else
                    	{
                    		Toast.makeText(getActivity(), "Please enter a name!", Toast.LENGTH_SHORT).show();
                    	}
                    	hideSoftKeyboard();
                    } 
                }); 
        
        Button catBtn = (Button) v.findViewById(R.id.editCatBtn);
        catBtn.setOnClickListener(new OnClickListener()
        {
        	/**
			 * This method creates a new CategoryFragment on edit cat button press
			 * @param v		View v
			 */
        	
        	@Override
        	public void onClick(View v)
        	{
        		FragmentManager fm = getFragmentManager();
        		FragmentTransaction ft = fm.beginTransaction();
        		CategoryFragment frag = new CategoryFragment();
        		ft.replace(R.id.frag, frag);
        		ft.commit();
        		
        	}
        });
        

		return v;
    } 
	
	/**
	* This method sets the different widgets to their proper values, ensuring accuracy of events
	* @param parent		
	* @param view
	* @param position
	* @param id 
	*/
	
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
	{
		if(parent.getId() == R.id.year)
		{
			
			c.set(Calendar.YEAR, (int) year.getSelectedItem());
			days.clear();
			for(int i = 1; i <= c.getActualMaximum(Calendar.DATE); i++)
			{
				days.add(i);
			}
			if(dayAdapter == null)
			{
				dayAdapter = new ArrayAdapter<Integer>(
						getActivity(), android.R.layout.simple_spinner_item, days);
				day.setAdapter(dayAdapter);
				day.setSelection(c.get(Calendar.DATE)-1);
			}
			else
				dayAdapter.notifyDataSetChanged();			
			
		}
		else if(parent.getId() == R.id.month)
		{
			c.set(Calendar.MONTH, (int) month.getSelectedItem()-1);
			days.clear();
			for(int i = 1; i <= c.getActualMaximum(Calendar.DATE); i++)
			{
				days.add(i);
			}
			if(dayAdapter == null)
			{
				dayAdapter = new ArrayAdapter<Integer>(
						getActivity(), android.R.layout.simple_spinner_item, days);
				day.setAdapter(dayAdapter);
			}
			else
				dayAdapter.notifyDataSetChanged();
		}
		else if(parent.getId() == R.id.day)
		{
			c.set(Calendar.DATE, (int) day.getSelectedItem());
		}
		else if(parent.getId() == R.id.hourStart)
		{
			endHours.clear();
			for(int i = position + 1; i < hours.length; i++)
			{
				endHours.add(hours[i]);
			}
			endHours.add("12AM");
			if(hourEndAdapter == null)
			{
				hourEndAdapter = new ArrayAdapter<String>(
					getActivity(), android.R.layout.simple_spinner_item, endHours);
				hourEnd.setAdapter(hourEndAdapter);
			}
			else
				hourEndAdapter.notifyDataSetChanged();
		}
		else if(parent.getId() == R.id.repeatDay)
		{
			if(position != 0)
			{
				day.setEnabled(false);
				month.setEnabled(false);
				year.setEnabled(false);
				c.set(Calendar.DAY_OF_WEEK, position);
			}
			else
			{
				day.setEnabled(true);
				month.setEnabled(true);
				year.setEnabled(true);
			}
		}
	}

	/**
	* This method hides input from the window.
	*/
	
	public void hideSoftKeyboard() {
	    InputMethodManager inputMethodManager = (InputMethodManager)  getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
	    inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
	} 

	/**
	* This method restores the navigation spinner and then chains to Fragment onDestroyView
	*/
	
	@Override
	public void onDestroyView()
	{
		ActionBar actionBar = getActivity().getActionBar();
    	actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    	super.onDestroyView();
	}

	
	
	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
	
	
}
